#include "movingAvg.h"


#define ROLLING_AVERAGE_WINDOW 6

// Light Sensor (analogue read) - Moving average
double        maverage_values[ROLLING_AVERAGE_WINDOW] = {0}; // all are zero as a start
int       maverage_current_position  = 0;
double      maverage_current_sum = 0;
int       maverage_sample_length = sizeof(maverage_values) / sizeof(maverage_values[0]);


// Updated
double  movingAvg( double newValue)
{
         //Subtract the oldest number from the prev sum, add the new number
        maverage_current_sum = maverage_current_sum - maverage_values[maverage_current_position] + newValue;

        //Assign the newValue to the position in the array
        maverage_values[maverage_current_position] = newValue;

        maverage_current_position++;
        
        if (maverage_current_position >= maverage_sample_length) { // Don't go beyond the size of the array...
            maverage_current_position = 0;
        }
                
        //return the average
        return maverage_current_sum / maverage_sample_length;

}
